package com.tanklab.signature.service.impl;

import com.tanklab.signature.service.SignatureStorageService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

@Service
public class SignatureStorageServiceImpl implements SignatureStorageService {

    @Value("${signature.upload-dir:./uploads/signatures/}")
    private String signatureUploadDir;

    @Value("${signature.access-path:/signatures/}")
    private String signatureAccessPath;

    @Value("${server.base-url:http://localhost:8010/signature}")
    private String baseUrl;

    @Override
    public String storeSignature(MultipartFile file) throws IOException {
        // 获取文件名称
        String originalFilename = StringUtils.cleanPath(file.getOriginalFilename());

        // 防止路径穿越攻击
        if (originalFilename.contains("..")) {
            throw new IOException("文件名包含非法路径字符");
        }

        // 确保目录存在
        File uploadDir = new File(signatureUploadDir);
        if (!uploadDir.exists()) {
            uploadDir.mkdirs();
        }

        // 生成随机文件名，保留原始文件扩展名
        String fileExtension = "";
        if (originalFilename.contains(".")) {
            fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
        }
        String newFilename = UUID.randomUUID().toString() + fileExtension;

        // 构建文件存储路径
        Path targetPath = Paths.get(signatureUploadDir, newFilename).normalize();

        // 存储文件
        Files.copy(file.getInputStream(), targetPath);

        // 返回可访问的文件路径
        return signatureAccessPath + newFilename;
    }

    @Override
    public boolean deleteSignature(String signatureUrl) {
        if (signatureUrl == null || signatureUrl.isEmpty()) {
            return false;
        }

        try {
            // 从URL中提取文件名
            String filename = signatureUrl.substring(signatureUrl.lastIndexOf("/") + 1);
            Path filePath = Paths.get(signatureUploadDir, filename);

            // 删除文件
            return Files.deleteIfExists(filePath);
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }
}